package com.yc;

import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Logger;

/**
 * 单线程版：聊天
 */
public class Test5_talk_Client {
    private static Logger log = Logger.getLogger(Test6_talkServer_runnable.class.getName());

    public static void main(String[] args) throws Exception {
        InetAddress ia = InetAddress.getByName("localhost");
        System.out.println(ia);
        Socket s = new Socket(ia, 10002);
        log.info("客户联接服务器成功" + s.getRemoteSocketAddress());
        //客户端通过健盘录入聊天信息
        try (Scanner keyboard = new Scanner(System.in); //标准输入流 -> 健盘
             //套接字流
             Scanner clientReader = new Scanner(s.getInputStream());
             PrintWriter pw = new PrintWriter(s.getOutputStream())
        ) {
            do {
                System.out.println("请输入客户端想对服务器说的话:");
                String line = keyboard.nextLine();
                //套接字提供的输出流
                pw.println(line);
                pw.flush();
                if ("bye".equalsIgnoreCase(line)) {
                    System.out.println("客户端要求主动断开与服务器的联接...");
                    break;
                }
                String response = clientReader.nextLine();
                System.out.println("服务器对客户端说:" + response);
                if ("bye".equalsIgnoreCase(response)) {
                    System.out.println("服务器主动断开与客户端的联接....");
                    break;
                }
            } while (true);
            System.out.println("在客户端正常结束聊天...");
        } catch (Exception e) {
            e.printStackTrace();
        }
            System.out.println("客户端关闭...");
        }
    }
